package org.penguin.study.bk.controller;

import lombok.extern.slf4j.Slf4j;
import org.penguin.study.bk.base.vo.Result;
import org.penguin.study.bk.dict.entity.SysDict;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Optional;

/**
 * @author chengyinghua
 */
@RestController
@RequestMapping("/study")
@Slf4j
public class StudyController {

    private static final String secretKey = "boooooooooom!!!!";
    private static final String salt = "1234567890123456";
    private static final String CHARSET = "utf-8";

    @RequestMapping(value = "/getString", method = RequestMethod.GET)
    public Result<?> getString() {
        // 直接返回对象
        return Result.ok(Optional.of("Java Optional对象"));
    }

    @RequestMapping(value = "/getNullable", method = RequestMethod.GET)
    public Result<?> getNullString() {
        return Result.ok(Optional.ofNullable(null));
    }

    @RequestMapping(value = "/getObject", method = RequestMethod.GET)
    public Result<?> getObject() {
        return Result.ok(Optional.of(SysDict.builder().dictCode("dict_object").dictName("字典对象").build()));
    }

    private static String arithmetic(String data, boolean isEncrypted) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(CHARSET), "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(salt.getBytes(CHARSET));
            if (isEncrypted) {
                cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
                return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes(CHARSET)));
            } else {
                cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
                return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes(CHARSET))));
            }
        } catch (Exception e) {
            return "";
        }
    }

    @GetMapping("/encrypt")
    public String encryptDemo() {
        return arithmetic("{\"user\":\"admin\",\"pwd\":\"123456\"}", true);
    }

    @GetMapping("/decrypt")
    public String DecryptDemo() {
        return arithmetic("hJjezgUoa2DsGQMigOAb0XN9CI1bT10zSDCnwfJJpYI=", false);
    }

}
